<template>
  <div class="common-container">
    <div class="common-content">
      <div v-if="goods" class="goods-detail-content">
        <!-- 商品图片和信息 -->
        <div class="goods-main-info">
          <div class="goods-detail-img">
            <img :src="goods.imgUrl || goods.img" :alt="goods.name">
          </div>
          <div class="goods-detail-info">
            <h1 class="goods-detail-name">{{ goods.goodsName }}</h1>
            <div class="goods-detail-price">¥{{ goods.price }}</div>
            <div class="goods-detail-desc">
              {{ goods.introduce || '暂无描述' }}
            </div>
            <div class="goods-detail-meta">
              <span class="meta-item">库存: {{ goods.storage || 0 }}</span>
              <span v-if="(goods.storage || 0) < 1" class="stock-out">库存不足</span>
              <span class="meta-item">销量: {{ goods.sellNum || 0 }}</span>
              <span class="meta-item">分类: {{ goods.cateName || '未分类' }}</span>
            </div>
            
            <!-- 数量选择 -->
            <div class="quantity-selector">
              <span class="quantity-label">数量:</span>
              <el-input-number 
                v-model="quantity" 
                :min="1" 
                :max="goods.storage || 999"
                :step="1"
                :disabled="(goods.storage || 0) < 1"
              ></el-input-number>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button type="primary" size="large" @click="addToCart(goods)" :disabled="(goods.storage || 0) < 1">加入购物车</el-button>
              <el-button type="success" size="large" @click="buyNow(goods)" :disabled="(goods.storage || 0) < 1">立即购买</el-button>
              <el-button size="large" @click="toggleCollect(goods)">
                <i v-if="isCollect" class="el-icon-star-on" style="color: #ffd04b"></i>
                <i v-else class="el-icon-star-off"></i>
                {{ isCollect ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 商品详情标签页 -->
        <el-tabs v-model="activeTab" style="margin-top: 30px;">
          <el-tab-pane label="商品详情" name="detail">
            <div class="goods-detail-tab">
              <!-- 商品详细描述 -->
              <div v-html="goods.introduce || '<p>暂无详细内容</p>'"></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="用户评价" name="comments">
            <div class="comments-tab">
              <div v-if="comments.length > 0">
                <div v-for="comment in comments" :key="comment.id" class="comment-item">
                  <div class="comment-user">
                    <img :src="comment.userAvatar" alt="用户头像" class="user-avatar">
                    <span class="user-name">{{ comment.userNickname }}</span>
                    <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
                  </div>
                  <div class="comment-content">{{ comment.content }}</div>
                  <div class="comment-score">
                    <el-rate :value="comment.score" disabled show-score></el-rate>
                  </div>
                </div>
              </div>
              <div v-else class="no-comments">
                <el-empty description="暂无评价"></el-empty>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 加载中 -->
      <div v-loading="loading" class="loading-container" element-loading-text="加载中..."></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "GoodsDetail",
  data() {
    return {
      goods: null,
      comments: [],
      quantity: 1,
      isCollect: false,
      activeTab: 'detail',
      loading: true
    };
  },
  created() {
    this.loadGoodsDetail();
  },
  methods: {
    loadGoodsDetail() {
      const goodsId = this.$route.params.id;
      this.loading = true;
      
      Promise.all([
          this.request.get(`/goods/${goodsId}`),
          this.request.get(`/comment/goods/${goodsId}`) // 修复API路径，将product改为goods
        ]).then(([goodsRes, commentsRes]) => {
          this.loading = false;
          
          if (goodsRes.code === 200) {
            // 直接使用后台返回的数据，不做字段映射
            this.goods = goodsRes.data;
            // 加载收藏状态
            this.checkCollectStatus();
          } else {
            this.$message.error(goodsRes.msg || '获取商品详情失败');
          }
        
        if (commentsRes.code === 200) {
          this.comments = commentsRes.data || [];
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取商品信息失败');
      });
    },
    
    checkCollectStatus() {
      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      if (user && this.goods) {
        this.request.get(`/collect/check?goodsId=${this.goods.id}`).then(res => {
          if (res.code === 200) {
            this.isCollect = res.data;
          }
        }).catch(() => {
          // 如果检查接口失败，尝试加载用户收藏列表
          this.request.get(`/collect/page`, {
            params: {
              userId: user.id
            }
          }).then(res => {
            if (res.code === 200) {
              const collects = res.data.records || [];
              this.isCollect = collects.some(collect => collect.goodsId === this.goods.id);
            }
          });
        });
      }
    },
    
    addToCart(goods) {
      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      if (!user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      // 使用与后端统一的购物车接口
      this.request.post("/cart", {
        userId: user.id,
        goodsId: goods.id,
        goodsName: goods.goodsName,
        price: goods.price,
        num: this.quantity,
        total: goods.price * this.quantity
      }).then(res => {
        if (res.code === 200) {
          this.showNotification('成功', '已加入购物车', 'success');
        } else {
          this.showNotification('失败', res.msg || '添加购物车失败', 'error');
        }
      }).catch(() => {
        this.showNotification('失败', '添加购物车失败', 'error');
      });
    },
    
    buyNow(goods) {
      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      if (!user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      // 直接跳转到订单确认页面
      this.$router.push({
        path: '/front/orderConfirm',
        query: {
          goodsId: goods.id,
          quantity: this.quantity
        }
      });
    },
    
    toggleCollect(goods) {
      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      if (!user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      if (this.isCollect) {
        // 取消收藏
        this.request.delete(`/collect?userId=${user.id}&goodsId=${goods.id}`).then(res => {
          if (res.code === 200) {
            this.isCollect = false;
            this.showNotification('成功', '已取消收藏', 'success');
          } else {
            this.showNotification('失败', res.msg || '取消收藏失败', 'error');
          }
        }).catch(() => {
          this.showNotification('失败', '取消收藏失败', 'error');
        });
      } else {
        // 添加收藏
        this.request.post('/collect', {
          userId: user.id,
          goodsId: goods.id,
          goodsName: goods.goodsName,
          goodsImg: goods.img,
          price: goods.price
        }).then(res => {
          if (res.code === 200) {
            this.isCollect = true;
            this.showNotification('成功', '收藏成功', 'success');
          } else {
            this.showNotification('失败', res.msg || '收藏失败', 'error');
          }
        }).catch(() => {
          this.showNotification('失败', '收藏失败', 'error');
        });
      }
    },
    
    showNotification(title, message, type) {
      // 使用Element UI的消息通知组件
      this.$message[`${type}`]({
        title: title,
        message: message,
        duration: 3000
      });
    },
    
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 20px;
}

.common-content {
  margin-bottom: 20px;
}

.goods-detail-content {
  background-color: #fff;
}

.goods-main-info {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.goods-detail-img {
  width: 400px;
  height: 400px;
  margin-right: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.goods-detail-img img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.goods-detail-info {
  flex: 1;
}

.goods-detail-name {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  line-height: 1.5;
}

.goods-detail-price {
  font-size: 28px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 20px;
}

.goods-detail-desc {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
  line-height: 1.8;
}

.goods-detail-meta {
  margin-bottom: 20px;
}

.meta-item {
  display: inline-block;
  margin-right: 30px;
  color: #909399;
  font-size: 14px;
}

.stock-out {
  display: inline-block;
  color: #f56c6c;
  font-size: 14px;
  margin-right: 30px;
  font-weight: bold;
}

.quantity-selector {
  margin-bottom: 30px;
}

.quantity-label {
  font-size: 16px;
  color: #303133;
  margin-right: 15px;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.action-buttons .el-button {
  min-width: 140px;
}

.goods-detail-tab {
  padding: 30px;
}

.comments-tab {
  padding: 30px;
}

.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 20px 0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-name {
  font-size: 16px;
  color: #303133;
  margin-right: 20px;
}

.comment-time {
  font-size: 14px;
  color: #909399;
}

.comment-content {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
  line-height: 1.8;
}

.comment-score {
  margin-bottom: 10px;
}

.no-comments {
  text-align: center;
  padding: 40px;
}

.loading-container {
  background-color: #fff;
  padding: 40px;
  text-align: center;
}

.loading-wrapper {
  min-height: 200px;
}
</style>